package client;

import interfaces.Core;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

/*
 * This class is for testing GUI
 */

public class ClientStartGUI extends JFrame
{
	private static final long serialVersionUID = -5199617154126219009L;
	private JButton buttonLogin;
	private JTextField nameField;
	private JPanel panel;
	private JLabel appName,statusLabel;
	private User user;
	private String url = "iiop://localhost:1060/";

	public ClientStartGUI()
	{
		super("Welcome to RMI-Store");
		setLocation(300,300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		getContentPane().setLayout(new GridLayout(3,1));

		buttonLogin = new JButton("Login");
		nameField = new JTextField("Name");

		panel = new JPanel(new GridLayout(2,1));
		panel.add(nameField);
		panel.add(buttonLogin);

		addButtonListener(buttonLogin);

		appName = new JLabel("RMI-Store");
		appName.setHorizontalAlignment(JLabel.CENTER); 

		statusLabel = new JLabel("Choose option");

		getContentPane().add(appName);
		getContentPane().add(panel);
		getContentPane().add(statusLabel);
		//pack();
		setSize(300, 300);
		setVisible(true);

	}

	public static void main(String[] args)
	{
		@SuppressWarnings("unused")
		ClientStartGUI g = new ClientStartGUI();
	}

	private void addButtonListener(JButton b)
	{
		b.addActionListener(new ActionListener() 
		{ 
			public void actionPerformed(ActionEvent ae) 
			{ 
				input(nameField.getText()+" choose "+ae.getActionCommand());
				String nameUser = nameField.getText();
				System.setProperty( "java.security.policy", "client.policy" );
				try
				{
					Context namingContext = new InitialContext();
					Core core = (Core) namingContext.lookup(url + "core");
					user = new User(nameUser);
					core.getCustomer(nameUser);
				}
				catch( NamingException e ) {
					System.out.println( "NamingError: " + e.getExplanation() ); 
				} catch( Exception e ) {
					System.out.println( "Error: " + e.getMessage() );
				}
				@SuppressWarnings("unused")
				ClientGUI gui = new ClientGUI(user,url);
				closeWindow();
			}
		});
	}

	private void closeWindow()
	{
		this.dispose();
	}

	private void input(String a)
	{
		statusLabel.setText(a + "! Please wait...");
	}    
}